package com.pro.schedule.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.pro.schedule.entity.User;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class TokenUtil {
    private final String privateKey="schedule";

    /**
     * 加密token.
     */
    public String getToken(User user) {
        //这个是放到负载payLoad 里面,魔法值可以使用常量类进行封装.
        return JWT
                .create()
                .withClaim("userId" ,user.getUserId().toString())
                .withClaim("userAccount", user.getUserAccount())
                .withClaim("userPhone", user.getUserPhone())
                .withClaim("timeStamp", System.currentTimeMillis())
                .sign(Algorithm.HMAC256(privateKey));
    }

    public Map<String, String> parseToken(String token) {
        HashMap<String, String> map = new HashMap<>();
        DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(privateKey))
                .build().verify(token);
        Claim userId = decodedjwt.getClaim("userId");
        Claim userAccount = decodedjwt.getClaim("userAccount");
        Claim userPhone = decodedjwt.getClaim("userPhone");
        Claim timeStamp = decodedjwt.getClaim("timeStamp");
        map.put("userId", userId.asString());
        map.put("userAccount", userAccount.asString());
        map.put("userPhone", userPhone.asString());
        map.put("timeStamp", timeStamp.asLong().toString());
        return map;
    }
}
